/*

Copyright (C) 2007 Thomas Geiger (tom.geiger@gmail.com)

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

*/

#include "globuscpp/CredManager.h"
#include "globuscpp/URL.h"
#include "globuscpp/XIOClient.h"

using namespace globus_common;
using namespace globus_xio;


#include "gt-ls.h"


static void usage() {
	error("gt_load('URL', 'format', 'varname', ...)");
}

DEFUN_DLD(gt_load, 
          args, 
          , 
          "Load Octave file from a Globus file resource."
          ) 
{	
	int argNum;
	string urlPath;
	string fileFormat = "ascii";
	stringstream output;
	load_save_format format;
	octave_value_list retval;
	
	// arg(0) => url
	argNum = args.length();
	if (argNum <= 1)  {
		error("Invalid arguments");	
		usage();
		return octave_value(false);
	}

	// check for existing certificate
	CredManager credMgr;	                                            
	if ( !credMgr.hasCredential() ) {
		cerr << "No valid credentials found." << endl;	
		return octave_value(false);
	} 

	// parse args	
	urlPath = args(0).string_value();
	if (argNum > 1) {
		fileFormat = args(1).string_value();	
	}
	
	// determine file format
	if ( !set_format(format, fileFormat) ) {
		cerr << "Invalid file format: " << fileFormat << endl;
		return octave_value(false);	
	}
	
	// construct url
	URL* g_url = URL::Create(urlPath);
	if (g_url == NULL) {
		return octave_value(false);	
	}
	
	// initialize client
	XIOClient* client = new XIOClient();
	client->setUrl(g_url);
	
	// fetch output
	bool success = client->receive(output);
	
	if (!success) {
		cerr << "Could not retrieve data. Network error?" << endl;
		return octave_value(false);	
	}
	
	// print output
	//input.flush();
	output.seekg(0);

	// reads ov from stream
	retval = load_data(output, format, args);

	delete client;
	delete g_url;

	return retval;
}
